//
//  CAVPublishArticleController.m
//  cascade-realm
//
//  Created by QSC on 4/6/24.
//

#import "CAVPublishArticleController.h"
#import "ImageCell.h"
#import "PictureBrowse.h"
#import "PlaceholderTextView.h"
@interface CAVPublishArticleController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong)UICollectionView * collectionView;
@property (nonatomic,strong)NSMutableArray * imageArray;
@property (nonatomic,strong)UITextField * titleTextField;
@property (nonatomic,strong)PlaceholderTextView * textView;
@end

@implementation CAVPublishArticleController

- (NSMutableArray *)imageArray{
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return  _imageArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton * postBtn = [UIButton ButtonWithFont:Font(12) color:[UIColor whiteColor] text:@"Post"];
    [self.navView addSubview:postBtn];
    [postBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(28);
        make.centerY.equalTo(self.backBtn);
        make.right.equalTo(self.navView).offset(-20);
    }];
    postBtn.layer.cornerRadius = 14;
    postBtn.clipsToBounds = YES;
    [Tool colorGradientLayerForView:postBtn frame:CGRectMake(0, 0, 50, 28) colors:@[Hex(0xB3E600),Hex(0xD4E600)] locations:@[@0.0,@1.0]];
    [postBtn addTarget:self action:@selector(postArticle) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(self.navView.mas_bottom).offset(16);
        make.height.mas_equalTo(120);
    }];
    
    
    UITextField * textFiled = [UITextField new];
    self.titleTextField = textFiled;
   
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Type your title." attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    textFiled.textColor = [UIColor colorWithWhite:0 alpha:0.5];
    textFiled.font = Font(20);
    [self.view addSubview:textFiled];
    [textFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(self.collectionView.mas_bottom).offset(15);
    }];
    
    UIView * line = [UIView new];
    line.backgroundColor = Hex(0xCCCCCC);
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1);
        make.left.right.equalTo(textFiled);
        make.top.equalTo(textFiled.mas_bottom).offset(16);
    }];
    
    PlaceholderTextView *textView = [PlaceholderTextView new];
    textView.placeholder = @"start creating your ideas.....";
    textView.placeholderColor = [UIColor colorWithWhite:0 alpha:0.5];
    [self.view addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(line.mas_bottom).offset(24);
        make.height.mas_equalTo(200);
    }];
    textView.backgroundColor = Hex(0xF6F8FA);
    textView.layer.cornerRadius = 20;
    textView.contentInset = UIEdgeInsetsMake(16, 13, 0, 0);
    self.textView = textView;
    
    UIImageView * imageV = [[UIImageView alloc]initWithImage:Img(@"bg_home")];
    [self.view addSubview:imageV];
    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-kBottomSafeHeight);
        make.right.equalTo(self.view);
        make.width.mas_equalTo(244);
        make.height.mas_equalTo(270);
    }];
}


- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        
        CGFloat ItemW = (ScreenW - 80)/3;
        
        layout.itemSize = CGSizeMake(ItemW, ItemW);
        
        layout.minimumInteritemSpacing = 20;
        layout.minimumLineSpacing = 20;
        //水平滚动
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        
        [collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
      
        _collectionView = collectionView;
    }
    
    return _collectionView;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.imageArray.count == 3) {
        return  3;
    }
    
    return self.imageArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
    cell.clipsToBounds = YES;
    cell.layer.cornerRadius = 8;
    if (indexPath.row == self.imageArray.count && self.imageArray.count != 3) {
        cell.centerImgv.hidden = NO;
        cell.imageV.hidden = YES;
        cell.deleteBtn.hidden = YES;
    }else{
        
        cell.imageV.image = self.imageArray[indexPath.row];
        cell.imageV.hidden = NO;
        cell.deleteBtn.hidden = NO;
        cell.centerImgv.hidden = YES;
    }
    
    WeakSelf
    cell.deleteBlock = ^{
        [weakSelf.imageArray removeObjectAtIndex:indexPath.row];
        [weakSelf.collectionView reloadData];
    };
    
   
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.imageArray.count && self.imageArray.count != 3) {
        WeakSelf
        [self getImageWithSelectedImageBlock:^(UIImage * _Nonnull image, NSData * _Nonnull imageData) {
           
            [weakSelf.imageArray addObject:image];
            [weakSelf.collectionView reloadData];
        }];
        
    }else{
        
        PictureBrowse *mybrowse = [[PictureBrowse alloc]init];
        
        mybrowse.imageArr = self.imageArray;
        mybrowse.frame = [UIScreen mainScreen].bounds;
        mybrowse.index = indexPath.row + 1;
        
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:mybrowse];
        
    }
}


- (void)postArticle{
    
    if (self.imageArray.count < 1) {
        [EasyTextView showText:@"images is empty"];
        return;
    }
    
    if (!self.titleTextField.hasText) {
        [EasyTextView showText:@"type your title"];
        return;
    }
    
    if (!self.textView.hasText) {
        [EasyTextView showText:@"type your ideas"];
        return;
    }
    
    CADataModel * model = [CADataModel new];
    model.title = self.titleTextField.text;
    model.content = self.textView.text;
    NSMutableArray * images = [self ImagesToloaclString:self.imageArray];
    model.cover = images.firstObject;
    [images removeFirstObject];
    model.images = images;
    model.key = [NSString stringWithFormat:@"%@--modelKey",[Tool randomStringWithNumber:10]];
    model.binduserId = CAUserInfo.shared.userInfo.userId;
    
    [Tool ShowLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [Tool HideLoading];
        [DBTool saveData:model.mj_JSONObject tag:model.key];
        
        [model addToPublishArticle];
        
        [EasyTextView showText:@"success"];
        
        [self.navigationController popViewControllerAnimated:YES];
    });
    
    

}

- (NSMutableArray *)ImagesToloaclString:(NSArray *)images{
    
    NSMutableArray * arr = [NSMutableArray array];
    SDImageCache * cache = [SDImageCache sharedImageCache];
    for (UIImage * image in images) {
        NSString * key = [NSString stringWithFormat:@"%@--image",[Tool randomStringWithNumber:10]];
        [cache storeImage:image forKey:key completion:^{
          
        }];
        [arr addObject:key];
    }
    
    
    return arr;
    
    
}
@end
